package com.yami.shop.api.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yami.shop.bean.model.ApiResult;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.util.AuthUtil;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.service.weChatLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/wxLogin")
@Api(tags = "微信授权登入")
@AllArgsConstructor
public class weChatLogin {

    @Autowired
    private UserMapper userMapper;
    /**
     * @throws
     * @title weChatLogin
     * @description 微信授权登录
     * @author Kuangzc
     * @updateTime 2019-9-12 16:00:51
     */
    @ApiOperation(value = "微信授权登录")
    /*@ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "code", value = "用户换取access_token的code，仅在ErrCode为0时有效", required = true, dataType = "String")
    })*/
    @GetMapping("/weChatLogin")
    protected ResponseEntity<Object> weChatLogin(@RequestParam String openid,String phone) {
        Integer coun = userMapper.selectCount(new QueryWrapper<User>()
        .eq("openid",openid));
        if(coun == 1){
            User user = userMapper.selectOne(new QueryWrapper<User>()
                    .eq("openid",openid));
            if (user.getSex().equals("M")){
                return ResponseEntity.ok(user);
            }else if (user.getSex().equals("F")){
                return ResponseEntity.ok(user);
            }
        }else if (coun == 0 && phone != null){
            User user = userMapper.selectOne(new QueryWrapper<User>()
                    .eq("user_mobile",phone));
            user.setOpenid(openid);
            userMapper.update(user,new QueryWrapper<User>()
            .eq("user_mobile",phone));
            return ResponseEntity.ok("绑定成功");
        }else if (coun == 0 && phone == null){
            return ResponseEntity.ok("该微信未被绑定");
        }
        return ResponseEntity.ok().build();
    }

}
